package main

import (
	"encoding/json"
	"log"
	"net/http"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

// 消息类型
type Message struct {
	Type      string      `json:"type"`      // 消息类型: join, leave, message, user_list
	UserID    string      `json:"userId"`    // 用户ID
	Username  string      `json:"username"`  // 用户名
	Content   string      `json:"content"`   // 消息内容
	Timestamp int64       `json:"timestamp"` // 时间戳
	Data      interface{} `json:"data"`      // 额外数据
}

// 客户端连接
type Client struct {
	ID       string
	Username string
	Conn     *websocket.Conn
	Hub      *Hub
	Send     chan []byte
}

// Hub 管理所有客户端连接
type Hub struct {
	clients    map[*Client]bool
	broadcast  chan []byte
	register   chan *Client
	unregister chan *Client
	mu         sync.RWMutex
}

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许跨域
	},
}

func newHub() *Hub {
	return &Hub{
		clients:    make(map[*Client]bool),
		broadcast:  make(chan []byte, 256), // 添加缓冲区避免阻塞
		register:   make(chan *Client),
		unregister: make(chan *Client),
	}
}

func (h *Hub) run() {
	for {
		select {
		case client := <-h.register:
			h.mu.Lock()
			h.clients[client] = true
			h.mu.Unlock()

			log.Printf("用户注册: %s (%s), 当前在线人数: %d", client.Username, client.ID, len(h.clients))

			// 通知所有人有新用户加入
			msg := Message{
				Type:      "join",
				UserID:    client.ID,
				Username:  client.Username,
				Timestamp: time.Now().Unix(),
			}
			h.broadcastMessage(msg)
			h.sendUserList()

		case client := <-h.unregister:
			h.mu.Lock()
			if _, ok := h.clients[client]; ok {
				delete(h.clients, client)
				close(client.Send)
			}
			h.mu.Unlock()

			// 通知所有人有用户离开
			msg := Message{
				Type:      "leave",
				UserID:    client.ID,
				Username:  client.Username,
				Timestamp: time.Now().Unix(),
			}
			h.broadcastMessage(msg)
			h.sendUserList()

		case message := <-h.broadcast:
			h.mu.RLock()
			for client := range h.clients {
				select {
				case client.Send <- message:
				default:
					close(client.Send)
					delete(h.clients, client)
				}
			}
			h.mu.RUnlock()
		}
	}
}

func (h *Hub) broadcastMessage(msg Message) {
	data, err := json.Marshal(msg)
	if err != nil {
		log.Printf("Error marshaling message: %v", err)
		return
	}
	h.broadcast <- data
}

func (h *Hub) sendUserList() {
	h.mu.RLock()
	defer h.mu.RUnlock()

	users := []map[string]string{}
	for client := range h.clients {
		users = append(users, map[string]string{
			"id":       client.ID,
			"username": client.Username,
		})
	}

	log.Printf("发送用户列表，共 %d 人: %v", len(users), users)

	msg := Message{
		Type:      "user_list",
		Timestamp: time.Now().Unix(),
		Data:      users,
	}
	data, _ := json.Marshal(msg)
	h.broadcast <- data
}

func (c *Client) readPump() {
	defer func() {
		c.Hub.unregister <- c
		c.Conn.Close()
	}()

	c.Conn.SetReadDeadline(time.Now().Add(60 * time.Second))
	c.Conn.SetPongHandler(func(string) error {
		c.Conn.SetReadDeadline(time.Now().Add(60 * time.Second))
		return nil
	})

	for {
		_, message, err := c.Conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
				log.Printf("error: %v", err)
			}
			break
		}

		var msg Message
		if err := json.Unmarshal(message, &msg); err != nil {
			log.Printf("Error unmarshaling message: %v", err)
			continue
		}

		msg.UserID = c.ID
		msg.Username = c.Username
		msg.Timestamp = time.Now().Unix()

		log.Printf("收到消息 from %s: %s", c.Username, msg.Content)

		c.Hub.broadcastMessage(msg)
	}
}

func (c *Client) writePump() {
	ticker := time.NewTicker(54 * time.Second)
	defer func() {
		ticker.Stop()
		c.Conn.Close()
	}()

	for {
		select {
		case message, ok := <-c.Send:
			c.Conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
			if !ok {
				c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}

			w, err := c.Conn.NextWriter(websocket.TextMessage)
			if err != nil {
				return
			}
			w.Write(message)

			if err := w.Close(); err != nil {
				return
			}

		case <-ticker.C:
			c.Conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
			if err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
				return
			}
		}
	}
}

func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}

	username := r.URL.Query().Get("username")
	if username == "" {
		username = "访客"
	}

	userID := r.URL.Query().Get("userId")
	if userID == "" {
		userID = generateID()
	}

	client := &Client{
		ID:       userID,
		Username: username,
		Conn:     conn,
		Hub:      hub,
		Send:     make(chan []byte, 256),
	}

	// 先启动 goroutines，再注册客户端
	// 这样可以确保 writePump 已经在监听 Send channel
	go client.writePump()
	go client.readPump()

	// 在 goroutines 启动后再注册
	client.Hub.register <- client
}

func generateID() string {
	return time.Now().Format("20060102150405") + string(rune(time.Now().Nanosecond()%1000))
}

func main() {
	hub := newHub()
	go hub.run()

	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		serveWs(hub, w, r)
	})

	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("OK"))
	})

	log.Println("WebSocket 服务器启动在 :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
